<?php

declare(strict_types=1);

namespace App\Repositories\Gashapon;

use App\Models\MainDB\Gashapon\PoolTemplate as Model;
use App\Traits\Singleton;

class PoolTemplateRepository
{
    use Singleton;

    public function getPoolTemplate(int $poolId)
    {
        $query = Model::query();
        $query->where(['pool_id' => $poolId]);
        $query->with(['gift']);
        $models = $query->get();
        $models->transform(function ($item) {
            $item->price       = $item->gift->price;
            $item->name        = $item->gift->name;
            $item->total_count = $item->count;
            return $item;
        });
        return $models;
    }

    public function all(array $filters = [], int $page = 1, int $perPage = 15)
    {
        $query = Model::query();
        $query->where($filters);
        $models = $query->paginate($perPage, ['*'], 'page', $page);
        return $models;
    }

    public function one(array $filters, bool $fail = false)
    {
        $query = Model::query();
        $query->where($filters);
        $model = $fail ? $query->firstOrFail() : $query->first();
        return $model;
    }

    public function find(int $id)
    {
        $model = $this->one(['id' => $id], true);
        return $model;
    }

    public function create(array $data)
    {
        $model = new Model();
        $model->fill($data);
        $model->save();
        $model->refresh();

        return $model;
    }

    public function update(int $id, array $data)
    {
        $model = $this->find($id);
        $model->fill($data);
        $model->save();
        return $model;
    }
}
